package com.abc.xxx.config.security;

import com.abc.xxx.model.User;
import com.abc.xxx.service.RoleService;
import com.abc.xxx.util.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 负责处理登录请求，如果请求url是'/login'，
 * 从请求体中解析json，解析出'username'、'password'两个字段，
 * 然后进行登录，登录成功后会向SecurityContext中存入一个Authentication
 */
@Getter
@Setter
@Slf4j
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    private JwtService jwtService;

    private RoleService roleService;

    public LoginFilter(JwtService jwtService,RoleService roleService) {
        this.jwtService = jwtService;
        this.roleService = roleService;
        setFilterProcessesUrl("/auth/login");
        setAuthenticationSuccessHandler(successHandler());
        setAuthenticationFailureHandler(new RestAuthenticationFailureHandler());
    }

    /**
     * 认证成功时触发的处理方法
     */
    public AuthenticationSuccessHandler successHandler() {
        return (req, res, auth) -> {
            User user = (User) auth.getPrincipal();
            // 查用户的数据权限
            List<Integer> userAccessibleDepts = roleService.findUserAccessibleDepts(
                    user.getDeptId(), user.getRoleId(), user.getDataScope());
            user.getAccessibleDepts().addAll(userAccessibleDepts);
            // 生成jwt token
            String token = jwtService.createToken(user.getName(), user.getJwtData());
            log.info("生成token：{}",token);
            Result json = Result.success("login").msg("登录成功").data("token", token);
            res.setStatus(200);
            res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            res.setHeader(AuthHeader.ACCESS_TOKEN,token);
            res.getWriter().write(json.toString());
        };
    }



    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        log.info("==>过滤器尝试登录, {} {}", request.getMethod(), request.getRequestURI());

        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String username;
        String password;

        try {
            BufferedReader reader = request.getReader();
            String body = reader.lines().collect(Collectors.joining("\n"));
            JSONObject json = JSON.parseObject(body);
            username = json.getString(getUsernameParameter());
            password = json.getString(getPasswordParameter());
            log.info("username: {} , password: {}", username, password);
        } catch (IOException e) {
            throw new AuthenticationServiceException("读取请求体内容时出错");
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

}
